package com.hd.trans.files.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.ConcatAdapter;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hd.trans.R;
import com.hd.trans.files.adapter.AudioPathAdapter;
import com.hd.trans.files.adapter.VideoPathAdapter;
import com.hd.trans.files.bean.Audio;
import com.hd.trans.files.bean.Video;
import com.hd.trans.files.model.FilesPathViewModel;
import com.hd.trans.files.model.PickingFileViewModel;

import java.util.List;

/**
 * 通过本地路径路径查找文件
 */
public class FilesPathFragment extends BaseFragment {

    private ProgressBar mLoadingProgressBar;
    private TextView mScanPathText;
    private RecyclerView mFilesRecyclerView;

    private AudioPathAdapter mAudioPathAdapter;
    private VideoPathAdapter mVideoPathAdapter;
    private FilesPathViewModel mViewModel;
    private PickingFileViewModel mPickingFileViewModel;

    public static FilesPathFragment newInstance() {
        return new FilesPathFragment();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_files_path;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mLoadingProgressBar = mRootView.findViewById(R.id.files_path_loading);
        mScanPathText = mRootView.findViewById(R.id.files_path_tv_scan_path);
        mFilesRecyclerView = mRootView.findViewById(R.id.files_path_list);
        mFilesRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mAudioPathAdapter = new AudioPathAdapter();
        mVideoPathAdapter = new VideoPathAdapter();
        mFilesRecyclerView.setAdapter(new ConcatAdapter(mAudioPathAdapter, mVideoPathAdapter));
        mFilesRecyclerView.setItemAnimator(null);

        mAudioPathAdapter.setOnItemClickListener((viewId, audio, position) -> onAudioItemClick(audio));
        mAudioPathAdapter.setOnItemChildClickListener((view1, audio, position) -> onAudioItemClick(audio));

        mVideoPathAdapter.setOnItemClickListener((viewId, video, position) -> onVideoItemClick(video));
        mVideoPathAdapter.setOnItemChildClickListener((viewId, video, position) -> onVideoItemClick(video));

        initCommonObserver();
    }

    private void initCommonObserver() {
        mPickingFileViewModel = new ViewModelProvider(requireActivity()).get(PickingFileViewModel.class);
        FilesPathViewModel.FilesPathViewModelFactory factory = new FilesPathViewModel.FilesPathViewModelFactory(
                requireActivity().getApplication()
        );
        mViewModel = new ViewModelProvider(this, factory).get(FilesPathViewModel.class);
        getLifecycle().addObserver(mViewModel);

        // 更新当前的文件路径
        mViewModel.getCurrentPathObserver().observe(
                getViewLifecycleOwner(),
                path -> mPickingFileViewModel.updateCurrentPath(path)
        );

        // 点击返回按钮加载相应的文件目录
        mPickingFileViewModel.getBackPressedObserver().observe(
                getViewLifecycleOwner(),
                path -> mViewModel.onBackPressed(path)
        );

        // 根据关键词进行搜索
        mPickingFileViewModel.getSearchObserver().observe(getViewLifecycleOwner(), keyWord -> {
            if (isResumed() || TextUtils.isEmpty(keyWord)) {
                mFilesRecyclerView.setVisibility(View.GONE);
                mViewModel.doSearch(keyWord);
            }
        });

        // 显示当前搜索的路径
        mViewModel.getScanPathObserver().observe(getViewLifecycleOwner(),
                scanPath -> mScanPathText.setText(scanPath)
        );

        // 显示 loading
        mViewModel.getLoadingObserver().observe(getViewLifecycleOwner(), enable -> {
            int visibility = enable ? View.VISIBLE : View.GONE;
            mScanPathText.setVisibility(visibility);
            mLoadingProgressBar.setVisibility(visibility);
        });
    }

    private void initVideoObserver() {

        // 更新视频数据
        mViewModel.getVideoDataObserver().observe(getViewLifecycleOwner(), this::showVideoData);

        // 更新选中的视频
        mPickingFileViewModel.getSelectedVideoObserver().observe(
                getViewLifecycleOwner(),
                videoPair -> mVideoPathAdapter.updateSelectedVideo(videoPair)
        );

        // 更新搜索视频数据
        mViewModel.getSearchVideoObserver().observe(getViewLifecycleOwner(), videos -> {
            if (videos.isEmpty()) {
//                setEmptyHintText(getString(R.string.picking_file_search_video_empty_result, mViewModel.getLastKeyWord()));
            }
            showVideoData(videos);
        });

        mPickingFileViewModel.getFilesSortObserver().observe(
                getViewLifecycleOwner(), method -> mVideoPathAdapter.sort(method)
        );
    }

    private void initAudioObserver() {

        // 显示当前文件夹和音频文件
        mViewModel.getAudiosDataObserver().observe(getViewLifecycleOwner(), this::showAudioData);

        // 选中音频文件状态更新
        mPickingFileViewModel.getSelectedAudiosObserver().observe(
                getViewLifecycleOwner(),
                audios -> mAudioPathAdapter.updateSelectedAudios(audios)
        );

        // 显示搜索音频的数据
        mViewModel.getSearchAudioObserver().observe(getViewLifecycleOwner(),
                audios -> {
                    if (audios.isEmpty()) {
//                        setEmptyHintText(getString(R.string.picking_file_search_audio_empty_result, mViewModel.getLastKeyWord()));
                    }
                    showAudioData(audios);
                }
        );

        mPickingFileViewModel.getFilesSortObserver().observe(
                getViewLifecycleOwner(), method -> mAudioPathAdapter.sort(method)
        );
    }

    private void onVideoItemClick(Video video) {
        if (video.isDirectory()) {
            // 加载目录
//            mViewModel.loadLocalVideos(video.getPath());
        } else {
            // 选中文件
            mPickingFileViewModel.updateSelectedVideo(video);
        }
    }

    private void onAudioItemClick(Audio audio) {
        if (audio.isDir()) {
            // 加载目录
            mViewModel.loadLocalAudios(audio.getUrl());
        } else {
            // 选中文件
            mPickingFileViewModel.updateSelected(audio);
        }
    }

    private void showEmptyView(boolean isEmpty) {
        if (isEmpty) {
            mFilesRecyclerView.setVisibility(View.GONE);
            setEmptyViewVisibility(View.VISIBLE);
        } else {
            mFilesRecyclerView.setVisibility(View.VISIBLE);
            setEmptyViewVisibility(View.INVISIBLE);
        }
    }

    private void showVideoData(List<Video> videos) {
        showEmptyView(videos.isEmpty());
        mVideoPathAdapter.submitList(videos);
    }

    private void showAudioData(List<Audio> audios) {
        showEmptyView(audios.isEmpty());
        mAudioPathAdapter.submitList(audios);
    }
}